<template>
	<div>
		<el-row :gutter="20" class="base-view">
			<el-col :span="12">
				<es-item v-bind="sourceData" @getDataType="getDataType" @getEsResp="getEsResp" />
			</el-col>
			<el-col :span="12">
				<es-item v-bind="targetData" @getDataType="getDataType" @getEsResp="getEsResp" />
			</el-col>
		</el-row>
		<div class="base-view multi-warpper">
			<el-row :gutter="30" style="margin-bottom: 15px">
				<el-col :span="1">
					<div>对比</div>
				</el-col>
				<el-col :span="4">
					<div>源数据字段</div>
				</el-col>
				<el-col :span="4">
					<div>数据类型</div>
				</el-col>
				<el-col :span="4">
					<div>目标数据字段</div>
				</el-col>
				<el-col :span="4">
					<div>数据类型</div>
				</el-col>
			</el-row>
			<div v-for="parentItem in dynamicItem" :key="parentItem.id">
				<el-row :gutter="30" type="flex" align="middle">
					<el-col :span="1">
						<el-checkbox v-model="parentItem.isCheck" :disabled="parentItem.isFirst" />
					</el-col>
					<el-col :span="4">
						<el-select size="mini" v-model="parentItem.sourceFieldName" placeholder="请选择" @change="handleSourceField(parentItem)">
							<el-option v-for="(item, index) in sourceArr" :key="index.id" :label="item.key" :value="item.key" :disabled="item.disabled" />
						</el-select>
					</el-col>
					<el-col :span="4">
						<el-input size="mini" v-model="parentItem.sourceTypeName" :disabled="true" />
					</el-col>
					<el-col :span="4">
						<el-select size="mini" v-model="parentItem.targetFieldName" placeholder="请选择" @change="handleTargetField(parentItem)">
							<el-option v-for="(item, index) in targetArr" :key="index.id" :label="item.key" :value="item.key" :disabled="item.disabled" />
						</el-select>
					</el-col>
					<el-col :span="4">
						<el-input size="mini" v-model="parentItem.targetTypeName" :disabled="true" />
					</el-col>
					<el-col :span="4" style="padding: 10px">
						<div v-if="parentItem.id == 0">
							<a style="color: #013adf" @click="addItem">+增加字段</a>
						</div>
						<div v-else>
							<a style="padding: 0 25px" @click="removeItem(parentItem)"><i class="el-icon-remove-outline" /></a>
						</div>
					</el-col>
				</el-row>
			</div>
		</div>
		<el-card>
			<div slot="header">
				<span><h4 style="display: inline-block">数据对比详情</h4></span>
				<div style="float: right; padding: 12px 0">
					<el-radio-group v-model="radioView" size="mini">
						<el-radio-button label="主键视图" />
						<el-radio-button label="差异视图" />
					</el-radio-group>
					<el-divider direction="vertical" />
					<el-button @click="compare" size="mini"> 开始对比</el-button>
				</div>
			</div>
			<div v-if="radioView === '主键视图' ? true : false">
				<el-table key="one" :data="mainData" width="100" max-height="500px" stripe style="width: 100%; margin-top: 20px">
					<el-table-column prop="id" label="序号" width="180" />
					<el-table-column prop="key" label="主键" />
					<el-table-column label="差异结果">
						<template slot-scope="scope">
							<span v-for="(i, index) in scope.row.value" :key="index" style="margin: 5px">
								<el-tag effect="plain">{{ i }}</el-tag>
							</span>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div v-else>
				<el-table key="two" :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" width="100" max-height="500px" stripe :span-method="objectSpanMethod" style="width: 100%; margin-top: 20px">
					<el-table-column prop="id" label="主键" width="180" />
					<el-table-column prop="name" label="差异字段" />
					<el-table-column prop="value1" label="源数据" />
					<el-table-column prop="value2" label="目标数据" />
				</el-table>
				<div class="base-pagination">
					<el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-size="pageSize" :page-sizes="[10, 20, 50, 100]" :current-page="currentPage" :total="tableData.length" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
				</div>
			</div>
		</el-card>
	</div>
</template>

<script>
import API from "@/api";
import EsItem from "./es_item.vue";
export default {
	name: "EsCompare",
	components: {
		EsItem
	},
	data() {
		return {
			sourceData: {
				id: 1,
				title: "源数据查询",
				options: []
			},
			targetData: {
				id: 2,
				title: "目标数据查询",
				options: []
			},
			sourceArr: [],
			sourceFirst: "",
			targetArr: [],
			targetFirst: "",
			dynamicItem: [
				{
					id: 0,
					isFirst: true,
					isCheck: true,
					sourceFieldName: "",
					sourceTypeName: "",
					targetFieldName: "",
					targetTypeName: ""
				}
			],
			source: "",
			target: "",
			tableData: [],
			spanArr: [], // 用于存放每一行记录的合并数
			radioView: "主键视图",
			currentPage: 1,
			pageSize: 10,
			mainData: []
		};
	},
	created() {
		// 级联设置 集群 索引
		API.getIndices()
			.then(resp => {
				if (!resp.success && this.$route.path === "/dataCompare/es2es") {
					this.$message.error("ES连接超时！");
					return;
				}
				this.sourceData.options = this.targetData.options = resp.data;
			})
			.catch(() => {
				// this.$message.error('连接服务器异常！')
			});
	},
	methods: {
		getDataType(data) {
			const bool = data.id === 1;
			// 首先每个item都恢复下初始
			this.dynamicItem = bool
				? this.dynamicItem.map(i => {
						[i.sourceFieldName, i.sourceTypeName] = "";
						return i;
				  })
				: this.dynamicItem.map(i => {
						[i.targetFieldName, i.targetTypeName] = "";
						return i;
				  });
			// 如果是空的就直接返回
			if (data.mappings === "") {
				bool ? (this.sourceArr = []) : (this.targetArr = []);
				return;
			}
			// 如果不为空需要设置默认的第一项
			const tmpArr = [];
			Object.keys(data.mappings).forEach((key, index) => tmpArr.push({ id: index, key: key, value: data.mappings[key].type, disabled: false }));
			// 设置当前操作的集群、索引对应的所有字段
			bool ? (this.sourceArr = tmpArr) : (this.targetArr = tmpArr);
			// 设置第一项默认值
			const tmpDynFirst = this.dynamicItem[0];
			const tmpFirst = tmpArr[0];
			tmpFirst.disabled = true;
			bool ? (this.sourceFirst = tmpFirst) : (this.targetFirst = tmpFirst);
			bool ? (tmpDynFirst.sourceFieldName = tmpFirst.key) : (tmpDynFirst.targetFieldName = tmpFirst.key);
			bool ? (tmpDynFirst.sourceTypeName = tmpFirst.value) : (tmpDynFirst.targetTypeName = tmpFirst.value);
		},
		handleSourceField(data) {
			// 如果第一项，需要先还原处理
			this.sourceArr.forEach(source => {
				if (data.id === 0 && this.sourceFirst === source) {
					source.disabled = false;
				}
			});
			// 再进行设置
			this.sourceArr.forEach(source => {
				if (source.key === data.sourceFieldName) {
					source.disabled = true;
					this.dynamicItem.map(i => {
						if (i.id === data.id) {
							i.sourceTypeName = source.value;
						}
					});
					if (data.id === 0) {
						this.sourceFirst = source;
					}
				}
			});
		},
		handleTargetField(data) {
			// 如果第一项，需要先还原处理
			this.targetArr.forEach(target => {
				if (data.id === 0 && this.targetFirst === target) {
					target.disabled = false;
				}
			});
			// 再进行设置
			this.targetArr.forEach(target => {
				if (target.key === data.targetFieldName) {
					target.disabled = true;
					this.dynamicItem.map(i => {
						if (i.id === data.id) {
							i.targetTypeName = target.value;
						}
					});
					if (data.id === 0) {
						this.targetFirst = target;
					}
				}
			});
		},
		addItem() {
			const ids = this.dynamicItem.map(i => i.id);
			this.dynamicItem.push({
				id: Math.max(...ids) + 1,
				isFirst: false,
				isCheck: false,
				sourceFieldName: "",
				sourceTypeName: "",
				targetFieldName: "",
				targetTypeName: ""
			});
		},
		removeItem(data) {
			this.sourceArr.forEach(source => {
				if (source.key === data.sourceFieldName) {
					source.disabled = false;
				}
			});
			this.targetArr.forEach(target => {
				if (target.key === data.targetFieldName) {
					target.disabled = false;
				}
			});
			this.dynamicItem = this.dynamicItem.filter(i => i.id !== data.id);
		},
		getEsResp(data) {
			data.id === 1 ? (this.source = data.mappings) : (this.target = data.mappings);
		},
		getSpanArr(data) {
			// data就是我们从后台拿到的数据
			for (var i = 0; i < data.length; i++) {
				if (i === 0) {
					this.spanArr.push(1);
					this.pos = 0;
				} else {
					// 判断当前元素与上一个元素是否相同
					if (data[i].id === data[i - 1].id) {
						this.spanArr[this.pos] += 1;
						this.spanArr.push(0);
					} else {
						this.spanArr.push(1);
						this.pos = i;
					}
				}
			}
		},
		objectSpanMethod({ rowIndex, columnIndex }) {
			if (columnIndex === 0) {
				const _row = this.spanArr[rowIndex];
				const _col = _row > 0 ? 1 : 0;
				// console.log(`rowspan:${_row} colspan:${_col}`)
				return {
					// [0,0] 表示这一行不显示， [2,1]表示行的合并数
					rowspan: _row,
					colspan: _col
				};
			}
		},
		compare() {
			if (this.source === "" || this.target === "") {
				this.$message.warning("请输入有效数据");
				return;
			}
			// 过滤掉未勾选的item并映射成后端需要的参数类型
			const trans = this.dynamicItem.filter(item => item.isCheck === true).map(item => ({ source: item.sourceFieldName, target: item.targetFieldName }));
			this.tableData = [];
			this.spanArr = [];
			this.mainData = [];
			API.compare({ source: this.source, target: this.target, trans }).then(resp => {
				const { sourceAndTarget, sourceDiff, targetDiff, diffValue } = { ...resp.data };
				this.$set(this.mainData, 0, { id: 1, key: "交集【源数据 目标数据】", value: sourceAndTarget });
				this.$set(this.mainData, 1, { id: 2, key: "差集【源数据 目标数据】", value: sourceDiff });
				this.$set(this.mainData, 2, { id: 3, key: "差集【目标数据 源数据】", value: targetDiff });
				this.tableData = diffValue;
				this.getSpanArr(this.tableData);
			});
		},
		handleSizeChange(pageSize) {
			this.pageSize = pageSize;
		},
		handleCurrentChange(currentPage) {
			this.currentPage = currentPage;
		}
	}
};
</script>

<style lang="scss" scoped>
.multi-warpper {
	font-size: 14px;
	font-weight: 500;
}
</style>
